package com.swak.boot.config.consistency.reliablemsg;

import static com.swak.boot.Application.APP_LOGGER;

import java.util.List;

import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;

import com.swak.Constants;
import com.swak.consistency.reliablemsg.config.ReliablemsgConfig;
import com.swak.consistency.reliablemsg.context.ReliableMsgContext;
import com.swak.consistency.reliablemsg.handle.ReliablemsgConsistencyHandler;
import com.swak.consistency.reliablemsg.resolve.DefReliableMsgContextResolver;
import com.swak.consistency.reliablemsg.schedule.ReliablemsgScheduler;
import com.swak.consistency.reliablemsg.transport.ReliableMsgLogTransport;

@Configuration
@ConditionalOnClass({ ReliableMsgContext.class })
@ConditionalOnProperty(prefix = Constants.APPLICATION_PREFIX, name = "enableReliableMsg", matchIfMissing = false)
@EnableConfigurationProperties(ReliablemsgProperties.class)
@Import({ MysqlReliablemsgLogStorageAutoConfiguration.class, RabbitmqReliableMsgLogTransportAutoConfiguration.class,
		RedisReliableMsgLogTransportAutoConfiguration.class, ReliablemsgManagerAutoConfiguration.class })
public class ReliablemsgAutoConfiguration {

	public ReliablemsgAutoConfiguration() {
		APP_LOGGER.debug("Loading Reliable Message");
	}

	/**
	 * 可靠消息 配置
	 * 
	 * @return
	 */
	@Bean
	public ReliablemsgConfig reliablemsgConfig(ReliablemsgProperties properties) {
		return new ReliablemsgConfig().setModule(properties.getModule()).setRetryTimes(properties.getRetryTimes())
				.setTimeout(properties.getTimeout());
	}

	/**
	 * 可靠消息 重试任务
	 * 
	 * @return
	 */
	@Bean
	public ReliablemsgScheduler reliablemsgScheduler(ReliablemsgConfig config) {
		return new ReliablemsgScheduler(config);
	}

	/**
	 * 可靠消息 处理器
	 * 
	 * @return
	 */
	@Bean
	public ReliablemsgConsistencyHandler reliablemsgConsistencyHandler(ReliablemsgConfig config,
			ObjectProvider<List<ReliableMsgLogTransport>> provider) {
		return new ReliablemsgConsistencyHandler(config, provider.getIfAvailable());
	}

	/**
	 * 托底的上下文处理器
	 * 
	 * @return
	 */
	@Bean
	public DefReliableMsgContextResolver defReliableMsgContextResolver() {
		return new DefReliableMsgContextResolver();
	}
}
